package jp.dev7.hongo2.controller;

import java.util.List;

import jp.dev7.hongo2.model.Question;
import jp.dev7.hongo2.proto.Hongo.QuestionListProto;
import jp.dev7.hongo2.proto.Hongo.QuestionProto;
import jp.dev7.hongo2.service.QuestionService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.KeyFactory;

public class DownloadController extends Controller {

    private QuestionService questionService = new QuestionService();

    @Override
    public Navigation run() throws Exception {

        List<Question> list = questionService.findAll();

        QuestionListProto.Builder result = QuestionListProto.newBuilder();
        for (Question q : list) {
            QuestionProto.Builder p = QuestionProto.newBuilder();

            p.setKey(KeyFactory.keyToString(q.getKey()));
            p.setContent(q.getContent().getValue());
            p.setSelection0(q.getSelection0());
            p.setSelection1(q.getSelection1());
            p.setSelection2(q.getSelection2());
            p.setSelection3(q.getSelection3());

            result.addItem(p);
        }

        response.setContentType("application/x-google-protobuf");
        result.build().writeTo(response.getOutputStream());
        response.flushBuffer();
        return null;
    }
}
